package com.promise.jokerdream.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.promise.jokerdream.config.game.BagGoodsUseGameConfig
import com.promise.jokerdream.config.game.BagGoodsUseType
import com.promise.jokerdream.database.UserDataManager
import com.promise.jokerdream.model.bag.BagGoods
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.work.manager.BagGoodsWorkManager
import com.promise.jokerdream.work.WorkResult
import com.promise.jokerdream.work.use.BagGoodsUseWork
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

/**
 * 背包页面ViewModel
 */
class BagViewModel(
    private val currentUserId: String?,
    private val onNavigateToExecutionLog: () -> Unit = {}
) : ViewModel() {
    
    private val gameApi = GameApi.getInstance()
    
    private val _bagGoods = MutableStateFlow<List<BagGoods>>(emptyList())
    val bagGoods: StateFlow<List<BagGoods>> = _bagGoods.asStateFlow()
    
    private val _searchQuery = MutableStateFlow("")
    val searchQuery: StateFlow<String> = _searchQuery.asStateFlow()
    
    private val _isLoading = MutableStateFlow(false)
    val isLoading: StateFlow<Boolean> = _isLoading.asStateFlow()
    
    init {
        // 自动加载背包物品
        loadBagGoods()
    }
    
    /**
     * 加载背包物品
     */
    fun loadBagGoods() {
        viewModelScope.launch {
            _isLoading.value = true
            try {
                if (currentUserId != null) {
                    gameApi.queryBagGoods(currentUserId).foldWithApiException(
                        onSuccess = { response ->
                            _bagGoods.value = response.bag
                        },
                        onFailure = { code, msg ->
                            // 处理错误，可以显示错误信息
                        }
                    )
                } else {
                    // 没有当前账号，清空物品列表
                    _bagGoods.value = emptyList()
                }
            } catch (e: Exception) {
                // 处理异常
            } finally {
                _isLoading.value = false
            }
        }
    }
    
    /**
     * 更新搜索查询
     */
    fun updateSearchQuery(query: String) {
        _searchQuery.value = query
    }
    
    /**
     * 使用物品
     */
    fun useItem(item: BagGoods) {
        viewModelScope.launch {
            // TODO: 实现使用物品的逻辑
            // 这里可以调用相应的API来使用物品
        }
    }
    
    /**
     * 一键开锦囊
     */
    fun oneClickUseStrategy() {
        if (currentUserId != null) {
            // 创建锦囊使用配置
            val config = BagGoodsUseGameConfig(
                enabledSetting = true,
                useType = BagGoodsUseType.STRATEGY
            )
            
            // 创建BagGoodsUseWork并添加到BagGoodsWorkManager
            val work = BagGoodsUseWork(config, currentUserId)
            val bagGoodsWorkManager = BagGoodsWorkManager.getInstance()
            bagGoodsWorkManager.addWork(work)
            
            // 立即跳转到执行记录页面
            onNavigateToExecutionLog()
        }
    }
    
    /**
     * 获取过滤后的物品列表
     */
    fun getFilteredItems(): List<BagGoods> {
        val query = _searchQuery.value
        return if (query.isBlank()) {
            _bagGoods.value
        } else {
            _bagGoods.value.filter { item ->
                item.name.contains(query, ignoreCase = true)
            }
        }
    }
}
